package com.wzt.lianfirecontrol.fragment.xuncha.xunchadevice;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.wzt.lianfirecontrol.R;
import com.wzt.lianfirecontrol.activity.BaseActivity;
import com.wzt.lianfirecontrol.adapter.xuncha.devicexuncha.XunChaDevicePlanAdapter;
import com.wzt.lianfirecontrol.bean.ConstData;
import com.wzt.lianfirecontrol.bean.recode.ListModel;
import com.wzt.lianfirecontrol.bean.recode.function.xuncha.devicexuncha.XunChaDevicePlanModel;
import com.wzt.lianfirecontrol.bean.recode.user.UserInfoModel;
import com.wzt.lianfirecontrol.fragment.BaseFragment;
import com.wzt.lianfirecontrol.http.HttpHelper;
import com.wzt.lianfirecontrol.http.json.ParseJsonData;
import com.wzt.lianfirecontrol.http.Url;
import com.wzt.lianfirecontrol.utils.JSONUtil;
import com.wzt.lianfirecontrol.utils.Utils;
import com.wzt.lianfirecontrol.view.InitView;
import com.wzt.lianfirecontrol.view.SuperSwipeRefreshLayout;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.LinkedList;

/**
 * 开始设备巡检页面
 */
public class StartDeviceXunChaFragment extends BaseFragment implements SuperSwipeRefreshLayout.OnSwipeRefreshListener {

    private BaseActivity activity;
    private Bundle bundle;
    private View itemContentView;

    private SuperSwipeRefreshLayout swipe_container;
    private RecyclerView rlv_info_list;
    private XunChaDevicePlanAdapter baseRecyclerAdapter;
    private LinearLayoutManager llm_info_list;

    /**
     * 列表底部数据加载状态
     */
    private View footerView;
    private LinearLayout ll_recycler_footer;
    private RelativeLayout rl_no_more_data;

    private View include_no_data;
    private View include_no_net;
    private View include_progress_bar;

    private static final int INFO_LIST_REQUEST_WHAT = 0;
    private int currentPage = 1;
    private boolean isNoMoreData = false;
    private boolean isListLoadOver = true;
    private int lastVisibleItem;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (null == itemContentView){
            bundle = getArguments();
            activity = getMyActivity();
            itemContentView = inflater.inflate(R.layout.f_start_xuncha_device, container, false);
            initView();
        }
        if (itemContentView.getParent() != null) {
            ((ViewGroup) itemContentView.getParent()).removeView(itemContentView);
        }
        return itemContentView;
    }

    private void initView() {

        swipe_container = itemContentView.findViewById(R.id.swipe_container);
        InitView.instance().initSuperSwipeLayout(swipe_container);
        swipe_container.setOnSwipeRefreshListener(this);
        swipe_container.setHeaderViewBackgroundColor(activity.getResources().getColor(R.color.divider_line_color));

        initListView();

        include_no_data = itemContentView.findViewById(R.id.include_no_data);
        include_progress_bar = itemContentView.findViewById(R.id.include_progress_bar);
        InitView.instance().initProgressBar(activity, include_progress_bar);
        include_no_net = itemContentView.findViewById(R.id.include_no_net);
        include_no_net.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                updateData();
            }
        });
    }

    private void initListView() {
        rlv_info_list = itemContentView.findViewById(R.id.rlv_info_list);
        llm_info_list = new LinearLayoutManager(activity);
        llm_info_list.setOrientation(LinearLayoutManager.VERTICAL);
        rlv_info_list.setLayoutManager(llm_info_list);

        baseRecyclerAdapter = new XunChaDevicePlanAdapter(activity);
        rlv_info_list.setAdapter(baseRecyclerAdapter);


        rlv_info_list.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE
                        && lastVisibleItem + 1 == baseRecyclerAdapter.getItemCount()) {
                    bottomLoadMore();
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                lastVisibleItem = llm_info_list.findLastVisibleItemPosition();
            }
        });

        initFooterView();
    }

    private void initFooterView() {
        footerView = LayoutInflater.from(activity).inflate(R.layout.item_recyclerview_footer, rlv_info_list, false);
        ll_recycler_footer = footerView.findViewById(R.id.ll_recycler_footer);
        ll_recycler_footer.setVisibility(View.GONE);
        rl_no_more_data = footerView.findViewById(R.id.rl_no_more_data);
        rl_no_more_data.setVisibility(View.GONE);
        baseRecyclerAdapter.setFooterView(footerView);
    }

    @Override
    public void onSwipeRefresh() {
        swipe_container.postDelayed(new Runnable() {
            @Override
            public void run() {
                swipe_container.setRefreshing(false);
                updateData();
            }
        }, 2000);
    }

    @Override
    public void onPushDistanceMoreAction(int distance) {

    }

    @Override
    public void onPullEnableMoreAction(boolean enable) {

    }

    @Override
    public void updateData() {
        super.updateData();
        isNoMoreData = false;
        currentPage = 1;
        initDeviceHttpHelper();
    }

    private void bottomLoadMore(){
        if (include_no_net.isShown() || include_no_data.isShown()
                || isNoMoreData || !isListLoadOver){
            return;
        }
        currentPage++;
        setFooterStyle(1);
        initDeviceHttpHelper();
    }

    /**
     * 获取列表
     */
    private void initDeviceHttpHelper() {
        if (Utils.hasNetwork(activity)){
            include_no_net.setVisibility(View.GONE);
        }else {
            include_no_net.setVisibility(View.VISIBLE);
            return;
        }
        isListLoadOver = false;
        include_progress_bar.setVisibility(View.VISIBLE);
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put(ConstData.COMPANYID, UserInfoModel.getCompandId(activity));
        hashMap.put(ConstData.PAGEINDEX, currentPage + "");
        hashMap.put(ConstData.PAGESIZE, ConstData.PAGE_20);

        HashMap<String, String> url_params = new HashMap<>();
        url_params.put(ConstData.JSONOBJECT, JSONUtil.mapToJSonStr(hashMap));
        HttpHelper homeListHttpHelper = new InfoListListHttpHelper(activity, Url.XUNCHA_DEVICE_BUILDING_URL, INFO_LIST_REQUEST_WHAT, handler, true, url_params);
        homeListHttpHelper.setParseJsonData(new InfoListParseJsonData());
        homeListHttpHelper.getHttpRequest(true);
    }

    private class InfoListListHttpHelper extends HttpHelper{
        public InfoListListHttpHelper(BaseActivity activity, String url, int what, Handler handler, boolean isPost, HashMap<String, String> params) {
            super(activity, url, what, handler, isPost, params);
        }
    }

    protected class InfoListParseJsonData extends ParseJsonData {

        public InfoListParseJsonData() {
        }

        @Override
        public void analyzeResult(String dataStr, Bundle bundle, int what) {
            try{
                switch (what){
                    case INFO_LIST_REQUEST_WHAT:
                        JSONObject jsonObject = new JSONObject(dataStr);
                        ListModel listModel = JSONUtil.jsonObjectToBean(jsonObject, ListModel.class);
                        if (jsonObject.has("list")) {
                            try {
                                if (baseRecyclerAdapter.getItemCount() + Integer.parseInt(listModel.getSize())
                                        >= Integer.parseInt(listModel.getTotal())) {
                                    isNoMoreData = true;
                                }
                            }catch (Exception e){}
                            LinkedList<XunChaDevicePlanModel> xunChaDevicePlanModels = (LinkedList<XunChaDevicePlanModel>) JSONUtil.jsonArrayToBeanList(
                                    new JSONArray(jsonObject.getString("list")), XunChaDevicePlanModel.class);
                            bundle.putSerializable("list", xunChaDevicePlanModels);
                            bundle.putBoolean(REQUEST_OK, true);
                            break;
                        }
                }
            } catch (Exception e) {
                e.printStackTrace();
                bundle.putBoolean(REQUEST_OK, false);
                bundle.putString(ERROR_MSG, ANALYZE_ERROR_MSG);
            }

        }
    }

    @Override
    protected void dealWithMyMsgs(Message msg) {
        super.dealWithMyMsgs(msg);
        Bundle bundle = msg.getData();
        if (!bundle.getBoolean(ParseJsonData.REQUEST_OK) ||
                !ParseJsonData.REQUEST_OK_CODE.equals(bundle.getString(ParseJsonData.ERROR_CODE))){
            //ToastUtils.showToast(activity, bundle.getString(ParseJsonData.ERROR_MSG));
            if (msg.what == INFO_LIST_REQUEST_WHAT) {
                include_progress_bar.setVisibility(View.GONE);
            }
            return;
        }
        switch (msg.what){
            case INFO_LIST_REQUEST_WHAT:
                include_progress_bar.setVisibility(View.GONE);
                setListData((LinkedList<XunChaDevicePlanModel>)bundle.getSerializable("list"));
                break;
        }
    }

    private void setListData(LinkedList<XunChaDevicePlanModel> list) {
        if (null == list || list.size() == 0){
            if (currentPage == 1){
                baseRecyclerAdapter.clear();
                include_no_data.setVisibility(View.VISIBLE);
            }else {
                setFooterStyle(2);
            }
            return;
        }
        include_no_data.setVisibility(View.GONE);
        setFooterStyle(0);
        if (currentPage == 1){
            baseRecyclerAdapter.clear();
        }
        baseRecyclerAdapter.addDatas(list);

    }

    /**
     * 0不显示 1正在加载中 2无更多数据
     * @param style
     */
    private void setFooterStyle(int style){
        switch (style){
            case 1:
                footerView.setVisibility(View.VISIBLE);
                ll_recycler_footer.setVisibility(View.VISIBLE);
                rl_no_more_data.setVisibility(View.GONE);
                break;
            case 2:
                footerView.setVisibility(View.VISIBLE);
                ll_recycler_footer.setVisibility(View.GONE);
                rl_no_more_data.setVisibility(View.VISIBLE);
                isNoMoreData = true;
                break;
            default:
                footerView.setVisibility(View.GONE);
                break;
        }
    }


}
